<?php

namespace common\models\datas;

use common\models\datas\Customer;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use common\components\extenders\MenuManage;

/**
 * This is the model class for table "{{%student}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $nickname
 * @property integer $age
 * @property integer $sex
 * @property integer $IDcard
 * @property integer $customer_id
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $site_id
 * @property integer $is_old
 */
class Student extends \common\components\bases\BaseModel
{
    public $is_reward;
    public $scholarship;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%student}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sex', 'customer_id', 'created_at', 'updated_at', 'site_id','is_old','age','is_reward'], 'integer'],
            [['img','blood_type','hobby','father_phone','father_company','mother_phone','mother_company','school','address','finish_studying',
                'source','card_number','company_type','main_contacts','main_phone','qrcode_url'], 'string'],
            [['scholarship'],'number'],
            [['birthday'],'date'],
            [['name','sex','IDcard'], 'required','on'=>['create','update']],
            [['sex', 'nickname'], 'safe', 'on' => ['studentApi']],
            [['name', 'nickname'], 'string', 'max' => 255],
            ['IDcard', 'match', 'pattern' => '/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/ ', 'message' => '身份证格式错误', 'on'=>['addidcard','create','update']],
            [['name','sex','birthday','IDcard'], 'required','on'=>['completeInfo','addidcard']],
            [['father_phone','mother_phone','main_phone'],'validate_mobile','on'=>['completeInfo']],
            [['card_number'], 'card_check','on' => ['card']],
            [['scholarship'], 'required','when' => function(){
                return $this->is_reward == 1;
            }],
            [['card_number'], 'required','on' => ['card']],
            [['card_number'], 'unique','on' => ['card']],
            [['IDcard'], 'unique','on' => ['create']],

//            [['card_number'],'validate_card_number','on'=>['completeInfo']]
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', 'ID'),
            'name' => Yii::t('common', '姓名'),
            'nickname' => Yii::t('common', '昵称'),
            'age' => Yii::t('common', '出生年份'),
            'sex' => Yii::t('common', '性别'),
            'IDcard' => Yii::t('common', '身份证号码'),
            'site_id' => Yii::t('common', '分店id'),
            'customer_id' => Yii::t('common', '会员编号'),
            'created_at' => Yii::t('common', '创建时间'),
            'updated_at' => Yii::t('common', 'Update At'),
            'img' => Yii::t('common', '头像'),
            'is_old' => Yii::t('common', '是否老生'),
            'birthday' => Yii::t('common', '出生年月'),
            'blood_type' => Yii::t('common', '血型'),
            'hobby' => Yii::t('common', '课外兴趣爱好'),
            'father_phone' => Yii::t('common', '父亲联系方式'),
            'father_company' => Yii::t('common', '父亲工作单位'),
            'mother_phone' => Yii::t('common', '母亲联系方式'),
            'mother_company' => Yii::t('common', '母亲工作单位'),
            'school' => Yii::t('common', '学校/幼儿园'),
            'address' => Yii::t('common', '家庭住址'),
            'finish_studying' => Yii::t('common', '已学习科目'),
            'intention_studying' => Yii::t('common', '感兴趣科目'),
            'source' => Yii::t('common', '渠道来源'),
            'card_number' => Yii::t('common', '卡号'),
            'company_type' => Yii::t('common', '父母工作单位类型'),
            'main_contacts' => Yii::t('common', '孩子的第一(主要)联系人'),
            'main_phone' => Yii::t('common', '主要联系人电话'),
            'qrcode_url' => Yii::t('common', '二维码地址'),
            'is_reward' => Yii::t('common', '增加奖学金'),
            'scholarship' => Yii::t('common', '奖学金金额'),
        ];
    }


    public function fields()
    {
        $fields = parent::fields();
        $fields['sex'] = function () {
            switch ($this->sex) {
                case 0:
                    return \Yii::t('common', '女');
                case 1:
                    return \Yii::t('common', '男');
            }
        };
        $fields['is_old'] = function () {
            switch ($this->is_old) {
                case 0:
                    return \Yii::t('common', '否');
                case 1:
                    return \Yii::t('common', '是');
            }
        };
        $fields['IDcard'] = function () {
            return str_replace(substr($this->IDcard, 6, 8), '********', $this->IDcard);
        };

        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['age'] =function(){
            if($this->age > 0){
                return (int)date('Y')-$this->age;
            }else{
                return 0;
            }
        };

        return $fields;
    }

    public function extraFields()
    {
        return [
            'customer_name' => function () {
                return isset($this->customer) ? $this->customer->name : null;
            },
            'common_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
        ];
    }

    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
        ]);
    }

    public function validate_mobile($attribute){
        if(strlen($this->$attribute)!=11&&!is_numeric($this->$attribute)){
            $this->addError($attribute, Yii::t('common', '请正确输入手机号码'));
        }
    }

    public function card_check($attribute)
    {
        if($attribute != null) {
            $data = Customer::find()->where(['card_id' => $this->$attribute])->andWhere("id!=$this->id")->one();
            if ($data != null || strlen($this->$attribute) != 10) {
                $this->addError($attribute, Yii::t('common', '此卡号已存在或卡号错误'));
            }
        }
    }

    public function validate_card_number($attribute){
        $card_attr = CardAttr::find()->where(['v_code' => $this->$attribute,'sendtype'=>0,'customer_id'=>NULL])
            ->andWhere(['in','status',[0,2]])->andWhere(['>', 'salesman_id', 0])->one();//仅针对实体卡
        /*激活码需要属于对应的类型*/
        if(empty($card_attr)){
            $this->addError($attribute, Yii::t('frontend', '对不起，该激活码无效'));
        }else{
            $site_id = $card_attr->site_id;
            if(!empty($site_id)){
                $site = Site::findOne($site_id);
                if(empty($site->mode)){
                    $this->addError($attribute, Yii::t('frontend', '对不起，当前激活码所属的类型不存在'));
                }else{
                    /*if($site->mode != $current_mode){
                        $this->addError($attribute, Yii::t('frontend', '激活码不属于当前'.$mode_name.'的类型'));
                    }*/
                }
            }
        }
    }
}
